package com.xin.chaingeneration.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xin.chaingeneration.common.ResponseEntity;
import com.xin.chaingeneration.entity.Node;
import com.xin.chaingeneration.entity.Product;
import com.xin.chaingeneration.service.NodeService;
import com.xin.chaingeneration.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/node")
public class NodeController {

    @Autowired
    NodeService nodeService;

    @Autowired
    ProductService productService;

    @PostMapping("/save")
    public ResponseEntity saveNode(@RequestBody Node node){

        nodeService.saveOrUpdate(node);

        return ResponseEntity.success("");

    }

    @PostMapping("/saveNodes")
    public ResponseEntity saveNodes(@RequestBody List<Node> nodes){
        Long productId = nodes.get(0).getProductId();
        Product product = productService.getById(productId);

        String productName = product.getProductName();

        Node nameNode = new Node();
        nameNode.setNodeName(productName);
        nameNode.setParentId(888l);
        nameNode.setProductId(productId);

        nodeService.save(nameNode);

        Long nameNodeId = nameNode.getId();

        for (Node node : nodes) {
            log.info(node.toString());
            if (node.getParentId()==null){
                node.setParentId(nameNodeId);
            }
        }

        nodeService.saveBatch(nodes);


        return ResponseEntity.success("");

    }

    @PostMapping("/getNode")
    public ResponseEntity<?> saveNode(@RequestBody(required = false) Product data) {
        Long productId = data.getId();

        LambdaQueryWrapper<Node> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Node::getProductId, productId);
        List<Node> list = nodeService.list(queryWrapper);
        ResponseEntity<List<Node>> responseEntity = new ResponseEntity<>();
        responseEntity.setData(list);
        responseEntity.setCode(1);
        responseEntity.setMsg("获取成功");

        return responseEntity;
    }

    @DeleteMapping("/deleteById/{id}")
    public ResponseEntity<String> deleteById(@PathVariable Long id ){

        LambdaQueryWrapper<Node> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Node::getProductId,id);

        nodeService.remove(queryWrapper);

        return ResponseEntity.success("deleted");
    }

}
